package com.lzx.adx.report.support.strategy.v3.channel;

import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import com.lzx.adx.report.annnotions.ProductType;
import com.lzx.adx.report.constant.ProductChannelConstant;
import com.lzx.adx.report.dto.OcpxAccountDTO;
import com.lzx.adx.report.dto.ProductConfigDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.util.URLEncoderDecoderTool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 海康互动
 */
@Component
@Slf4j
@ProductType(ProductChannelConstant.HKHD)
public class HaiKangHuDongReport extends AbstractProductReport {

    @Override
    public String execute(ReportDTO reportDTO, OcpxAccountDTO ocpxAccountDTO, ProductConfigDTO productConfigDTO) {
        Map<String, Object> params = new HashMap<>();
        params.put("clickid", reportDTO.getBizRequestId());
        if (StringUtils.isNotBlank(reportDTO.getImei()) && !StringUtils.contains(reportDTO.getImei(), "__")) {
            params.put("imei", reportDTO.getImei());
        }
        if (StringUtils.isNotBlank(reportDTO.getImeiSum()) && !StringUtils.contains(reportDTO.getImeiSum(), "__")) {
            params.put("imei_md5", reportDTO.getImeiSum().toLowerCase());
        }
        if (StringUtils.isNotBlank(reportDTO.getOaid()) && !StringUtils.contains(reportDTO.getOaid(), "__")) {
            params.put("oaid", reportDTO.getOaid());
        }
        if (StringUtils.isNotBlank(reportDTO.getHash_android_id()) && !StringUtils.contains(reportDTO.getHash_android_id(), "__")) {
            params.put("android_id", reportDTO.getHash_android_id());
        }
        params.put("ip", StringUtils.isNotBlank(reportDTO.getIp()) ? reportDTO.getIp() : "");
        params.put("ua", StringUtils.isNotBlank(reportDTO.getUser_agent()) ? URLUtil.encode(reportDTO.getUser_agent()) : "");
        params.put("callback", URLEncoderDecoderTool.encodeURL(String.format(productConfigDTO.getCallbackUrl(), reportDTO.getBizRequestId())));
        String urlParams = URLUtil.buildQuery(params, StandardCharsets.UTF_8);
        String finalUrl = ocpxAccountDTO.getReportUrl() + "&" + urlParams;
        log.info("账号为{} 请求id[{}] 请求海康互动产品端的完整地址为 {}", ocpxAccountDTO.getId(), reportDTO.getBizRequestId(), finalUrl);
        String body = HttpUtil.createGet(finalUrl).execute().body();
        log.info("账号为{} 请求id[{}] 请求海康互动产品端，响应的结果为{}", ocpxAccountDTO.getId(), reportDTO.getBizRequestId(), body);
        ocpxAccountDTO.setFinalURL(finalUrl);
        return body;
    }
}